package com.baizw.cultivation.common.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baizw.cultivation.common.annotation.NoRepeatSubmit;
import com.baizw.cultivation.common.exception.GlobalException;
import com.baizw.cultivation.module.admin.entity.UserEntity;
import com.baizw.cultivation.util.RedisUtil;
import com.baizw.cultivation.util.ShiroUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 表单重复提交拦截器
 *
 * @author 剧终1204
 * @version V1.0
 * @date 2020年07月06日 11:23
 */
@Slf4j
public class NoRepeatSubmitInterceptor extends HandlerInterceptorAdapter {
    private static final String REPEAT_URL_TEMPLATE = "REPEAT_URL_{}#{}";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            Method method = ((HandlerMethod) handler).getMethod();
            NoRepeatSubmit annotation = method.getAnnotation(NoRepeatSubmit.class);
            if (annotation != null) {
                // 获取当前用户
                // 根据当前用户获取此次URL是否为重复提交
                UserEntity userEntity = ShiroUtil.getUser();
                if (userEntity == null) {
                    log.error("当前用户未登录");
                    throw new GlobalException("当前用户未登录");
                }

                String repeatUrl = StrUtil.format(REPEAT_URL_TEMPLATE, userEntity.getId(), request.getServletPath());
                RedisUtil redisUtil = SpringUtil.getBean(RedisUtil.class);
                if (redisUtil.get(repeatUrl) == null) {
                    redisUtil.set(repeatUrl, request.getServletPath(), annotation.time());
                    return true;
                }
                log.error("请勿重复提交");
                throw new GlobalException("请勿重复提交");
            }
        }
        return super.preHandle(request, response, handler);
    }
}
